using ChuTiJingTai.Models;
using System.Text;
using LogLevel = ChuTiJingTai.Models.LogLevel;

namespace ChuTiJingTai.Services
{
    /// <summary>
    /// 日志服务实现
    /// </summary>
    public class LogService : ILogService
    {
        private readonly ILocalStorageService _localStorage;

        public LogService(ILocalStorageService localStorage)
        {
            _localStorage = localStorage;
        }

        public async Task LogInfoAsync(string message, string module = "", string? details = null)
        {
            await AddLogAsync(LogLevel.Info, message, module, details);
        }

        public async Task LogWarningAsync(string message, string module = "", string? details = null)
        {
            await AddLogAsync(LogLevel.Warning, message, module, details);
        }

        public async Task LogErrorAsync(string message, string module = "", string? details = null)
        {
            await AddLogAsync(LogLevel.Error, message, module, details);
        }

        public async Task LogDebugAsync(string message, string module = "", string? details = null)
        {
            await AddLogAsync(LogLevel.Debug, message, module, details);
        }

        private async Task AddLogAsync(string level, string message, string module, string? details)
        {
            var logEntry = new LogEntry
            {
                Level = level,
                Message = message,
                Module = module,
                Details = details,
                Timestamp = DateTime.Now
            };

            await _localStorage.AddLogAsync(logEntry);
        }

        public async Task<List<LogEntry>> GetLogsAsync()
        {
            var logs = await _localStorage.GetLogsAsync();
            return logs.OrderByDescending(l => l.Timestamp).ToList();
        }

        public async Task<List<LogEntry>> GetLogsByLevelAsync(string level)
        {
            var logs = await _localStorage.GetLogsByLevelAsync(level);
            return logs.OrderByDescending(l => l.Timestamp).ToList();
        }

        public async Task ClearLogsAsync()
        {
            await _localStorage.ClearLogsAsync();
        }

        public async Task<string> ExportLogsAsync()
        {
            var logs = await GetLogsAsync();
            var sb = new StringBuilder();
            
            sb.AppendLine("=== AI辅助学习平台日志导出 ===");
            sb.AppendLine($"导出时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
            sb.AppendLine($"日志条数: {logs.Count}");
            sb.AppendLine();

            foreach (var log in logs)
            {
                sb.AppendLine($"[{log.Timestamp:yyyy-MM-dd HH:mm:ss}] [{log.Level}] [{log.Module}]");
                sb.AppendLine($"消息: {log.Message}");
                if (!string.IsNullOrEmpty(log.Details))
                {
                    sb.AppendLine($"详情: {log.Details}");
                }
                sb.AppendLine();
            }

            return sb.ToString();
        }
    }
} 